//
//  ServicePlatformViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/8.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import CRRefresh

class ServicePlatformViewController: BaseViewController {

    @IBOutlet var bannerView: UIView!
    
    @IBOutlet var segmentView: UIView!
    
    var plaformSegment:YJSegmentedControl?
    
    @IBOutlet var plaformTableview: UITableView!
    
    var taskStatus = 0  // 0 求帮忙  1已搞定 = 0
    
    var platformTasks:[PlatformTaskModel]?
    var banners:[PhotoModel]?
    var bView:HW3DBannerView?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        page = 1
        requstPlatformTaskList(page: page!, status: taskStatus)
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configView()
        initSegmentControl()
        initBannerView()
        requstBannerData()
    }
    
    func initBannerView() -> Void {
        bView = HW3DBannerView.initWithFrame(CGRect(x: 0, y: 0, width: kScreenWidth, height: self.bannerView.frame.height), imageSpacing: 10, imageWidth: kScreenWidth - 50)
        bView?.initAlpha = 0.5
        bView?.imageRadius = 10
        bView?.imageHeightPoor = 10
//        bView?.placeHolderImage =
        
        bView?.clickImageBlock = { (index) in
            print(index)
        }
        self.bannerView.addSubview(bView!)
        
    }
    
    func initSegmentControl() -> Void {
        let btnDataSource = ["求帮忙","已签约"]
        plaformSegment = YJSegmentedControl.init(frame: CGRect(x:0,y:0,width:kScreenWidth - 100,height:self.segmentView.frame.height), titleDataSource: btnDataSource, backgroundColor: UIColor.clear, titleColor: UIColor.white, titleFont: UIFont.systemFont(ofSize: 14), select: BaseColor.NavColor, buttonDownColor: BaseColor.NavColor, delegate: self)
        plaformSegment?.center.x = kScreenWidth/2
        self.segmentView.addSubview(plaformSegment!)
    }
    
    func configView() -> Void {
        plaformTableview.delegate = self
        plaformTableview.dataSource = self
        plaformTableview.separatorStyle = .none
        plaformTableview.showsVerticalScrollIndicator = false
        plaformTableview.register(UINib(nibName: "ServicePlatformTableViewCell", bundle: nil), forCellReuseIdentifier: "platformCell")
        plaformTableview.cr.addHeadRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol) { [weak self] in
            page = 1
            self?.requstPlatformTaskList(page:page!, status: (self?.taskStatus)!)
        }
        plaformTableview.cr.addFootRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol)  { [weak self] in
            page! += 1
            self?.requstPlatformTaskList(page: page!, status: (self?.taskStatus)!)
        }
    }
    //跳转查看需求页面
    func pushLookServiceTaskVC(model:PlatformTaskModel) -> Void {
        let lookServiceTaskVC = LookServiceViewController()
        lookServiceTaskVC.title = "需求详情"
        lookServiceTaskVC.taskModel = model
        self.navigationController?.pushViewController(lookServiceTaskVC, animated: true)
    }
    //跳转修改需求页面
    func pushEditServiceTaskVC(model:PlatformTaskModel) -> Void {
        let editServiceTaskVC = EditServiceTaskViewController()
        editServiceTaskVC.title = "我的需求详情"
        editServiceTaskVC.taskModel = model
        self.navigationController?.pushViewController(editServiceTaskVC, animated: true)
    }
    //网络请求
    //获取需求列表
    func requstPlatformTaskList(page:Int,status:Int) -> Void {
        
        Alamofire.request(platformTaskListUrl, method:.post, parameters: ["status":status,"page": page,"uid":UserModel.shareUser.data?.uid ?? String()])
            .responseString { response in
                
                self.plaformTableview?.cr.endHeaderRefresh()
                self.plaformTableview?.cr.endLoadingMore()
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<PlatformTaskModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:

                        if page == 1 {
                            self.platformTasks?.removeAll()
                            self.platformTasks = basemodel.data?.data
                        }else {
                            if ((basemodel.data?.data?.count)! > 0) {
                                self.platformTasks! += (basemodel.data?.data)!
                            }else {
                                return
                            }
                        }
                        self.plaformTableview.reloadData()
                        print("数据成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
                
                
        }
    }
    //获取banner图data
    func requstBannerData() -> Void {
        
        Alamofire.request(platformBannerUrl, method:.post, parameters: ["type":"18"])
            .responseString { response in
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<PhotoModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        if (basemodel.data?.data?.count)! > 0 {
                            self.banners = basemodel.data?.data
                            if self.banners != nil {
                                var thumbs = [String]()
                                var jumpurls = [String]()
                                var linkurls = [String]()
                                for (model) in self.banners! {
                                    
                                    thumbs.append(model.thumb)
                                    jumpurls.append(model.jumpurl)
                                    linkurls.append(model.linkurl)
                                }
                                self.bView?.data = thumbs
                            }
                            
                        }
                        
                        print("数据成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
                
                
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

extension ServicePlatformViewController: YJSegmentedControlDelegate,UITableViewDelegate,UITableViewDataSource {
    
    func segumentSelectionChange(_ selection: Int) {
        page = 1
        taskStatus = selection
        requstPlatformTaskList(page: page!, status: taskStatus)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.platformTasks?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "platformCell", for: indexPath) as! ServicePlatformTableViewCell
        cell.selectionStyle = .none
        cell.backgroundColor = UIColor.clear
        let model = platformTasks![indexPath.row]
        cell.priceLabel.text = "预算:¥" + model.budget_money
        cell.userHeaderImageView.sd_setImage(with: (NSURL(string:(model.shead_url))! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
        cell.contentLabel.text = model.describe
        cell.userNameLabel.text = model.sname
        cell.taskTypeLabel.text = model.name
        if taskStatus == 0 {
            cell.cellTypeLabel.text = "我来帮忙"
        }else {
            cell.cellTypeLabel.text = "详情"
        }
        cell.creatTimeLabel.text = model.create_at;
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ScaleHeight(130)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = platformTasks![indexPath.row]
        
        if model.state == "0"{//0 与我无关
            
            switch taskStatus {
            case 0://求帮忙
                let giveTaskVC = GiveTaskViewController()
                giveTaskVC.taskModel = model
                giveTaskVC.title = "给出方案"
                self.navigationController?.pushViewController(giveTaskVC, animated: true)
            case 1://已完成
               self.pushLookServiceTaskVC(model: model)
            default:
               break
            }
            
            
           
        }else if model.state == "1"{//1 我发布
            
            switch taskStatus {
            case 0://求帮忙
                self.pushEditServiceTaskVC(model: model)
            case 1://已完成
                self.pushLookServiceTaskVC(model: model)
            default:
                break
            }
        }else {//2 我参与
            self.pushLookServiceTaskVC(model: model)
        }
    }
}

